﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using RHD.Common.Web.Components.Accordion;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class AccordionExtension {
		public static MvcHtmlString Accordion(this HtmlHelper htmlHelper, string id, Action<AccordionItems> itemsHandle, Action<AccordionBuilder> optionsHandle = null, object htmlAttributes = null) {
			AccordionItems items = new AccordionItems();
			if (itemsHandle != null)
				itemsHandle(items);

			AccordionBuilder options = new AccordionBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			TagBuilder div = GetAccordion(id, items, options);
			if (htmlAttributes != null)
				div.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));

			RegisterScript(htmlHelper, id);
			return MvcHtmlString.Create(div.ToString());
		}

		private static TagBuilder GetAccordion(string id, AccordionItems items, AccordionBuilder options) {
			TagBuilder accordion = new TagBuilder("div");
			accordion.AddCssClass("panel-group");
			accordion.GenerateId(id);

			int i = 1;
			foreach (AccordionItemBuilder item in items.GetItems()) {
				TagBuilder panel = new TagBuilder("div");
				panel.AddCssClass("panel panel-default");

				TagBuilder heading = new TagBuilder("div");
				heading.AddCssClass("panel-heading");

				TagBuilder title = new TagBuilder("h4");
				title.AddCssClass("panel-title");

				TagBuilder link = new TagBuilder("a");
				link.Attributes["data-toggle"] = "collapse";
				link.Attributes["data-parent"] = "#" + id;
				link.Attributes["href"] = "#" + id + "_" + i;
				link.SetInnerText(item.label);

				title.InnerHtml = link.ToString();
				heading.InnerHtml = title.ToString();

				TagBuilder collapse = new TagBuilder("div");
				collapse.GenerateId(id + "_" + i);
				collapse.AddCssClass("panel-collapse collapse");
				if (options.expand || item.expand) {
					collapse.AddCssClass("in");
				}

				TagBuilder body = new TagBuilder("div");
				body.AddCssClass("panel-body");
				body.SetInnerText(item.html);

				collapse.InnerHtml = body.ToString();

				panel.InnerHtml = heading.ToString() + collapse.ToString();
				accordion.InnerHtml += panel.ToString();

				i++;
			}

			return accordion;
		}

		private static void RegisterScript(HtmlHelper htmlHelper, string id) {
			htmlHelper.AddScript(string.Format("$('#{0}').collapse();", id));
		}
	}
}